//
//  JPStatusRetweetView.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/24.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit
import YYText

class JPStatusRetweetView: UIView {
    
    //底部约束
    private var bottomConstraint: Constraint?

    var statusViewModel: JPStatusViewModel? {
        didSet {
            contentLabel.attributedText = statusViewModel?.retweetAttributeString
            
            //多图
            bottomConstraint?.uninstall()
            
            if let picUrls = statusViewModel?.status?.retweeted_status?.pic_urls, picUrls.count > 0 {
                pictureView.isHidden = false
                self.snp_updateConstraints(closure: { (make) in
                    bottomConstraint = make.bottom.equalTo(pictureView).offset(JPHomeTableViewCellMargin).constraint
                    
                })
                
                pictureView.picUrls = picUrls
                
            }else {
                
                pictureView.isHidden = true
                self.snp_updateConstraints(closure: { (make) in
                    bottomConstraint = make.bottom.equalTo(contentLabel).offset(JPHomeTableViewCellMargin).constraint
                })
            }
        }
    }
    
    
    
    //  MARK: --    懒加载
    private lazy var contentLabel: YYLabel = {
        let label = YYLabel()
        label.preferredMaxLayoutWidth = screenWidth - 2 * JPHomeTableViewCellMargin
        label.numberOfLines = 0
    
        return label
    }()
    
    //图片
    lazy var pictureView: JPStatusPictureView = {
        let pictureView = JPStatusPictureView()
        return pictureView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //  添加控件设置约束
    private func setupUI() {
        
        contentLabel.highlightTapAction = {(containerView, text, range, rect) in
            let targetStr = (text.string as NSString).substring(with: range)
            if targetStr.hasPrefix("http") {
                print("打开对应网页")
            }
        }
        
        addSubview(contentLabel)
        addSubview(pictureView)
        
        contentLabel.snp_makeConstraints { (make) in
            make.top.equalTo(self).offset(JPHomeTableViewCellMargin)
            make.leading.equalTo(self).offset(JPHomeTableViewCellMargin)
            make.width.equalTo(ScreenWidth - 2 * JPHomeTableViewCellMargin)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.top.equalTo(contentLabel.snp_bottom).offset(JPHomeTableViewCellMargin)
            make.left.equalTo(contentLabel)
        }
        //  关键约束 -> 指定当前视图的底部约束=转发微博内容底部的约束+间距
        self.snp_makeConstraints { (make) in
            bottomConstraint = make.bottom.equalTo(pictureView).offset(JPHomeTableViewCellMargin).constraint
        }
    }
}
